const {
  delEvent
} = require("../../pages/Common/eventProxy.js");

// pages/User/Me/me.js
const app = getApp(),
  {
    $resHost,
    $config
  } = app.globalData,
  $extConfig = xhs.getExtConfigSync(),
  emInfo = require("../../pages/Common/getEmployee.js"),
  {
    initPay,
    subscribeMessage,
    initFn
  } = require("../../pages/Common/pay.js"),
  commonBehaviors = require("../commonBehaviors.js");
Component({
  behaviors: [commonBehaviors],
  /**
   * 组件的属性列表
   */
  properties: {
    isEmployee: {
      type: Boolean,
      value: false
    },
    points: {
      type: Number,
      value: 0
    },
    memberlevel: {
      type: String,
      value: "铜牌"
    },
    topOrgId: {
      type: String,
      value: "0"
    },
    coins: {
      type: Number,
      value: 0
    },
    changeTab: {
      type: String,
      value: "",
      observer(changeTab) {
        if (changeTab == "me") {
          this.getNotRead();
        }
      }
    },
    isEdit: {
      type: Boolean,
      value: false,
      observer(isEdit) {
        if (isEdit) {
          emInfo().then(res => {
            let user = res.userInfo;
            this.setData({
              user
            });
            this.triggerEvent("setFalse", {
              isEdit: false
            });
          });
        }
      }
    },
    employeeWaitActivateFlag: Boolean
  },
  attached() {
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    this.getDateForm().then(() => {
      this.dateInit();
    });
    this.setData({
      year: year,
      month: month,
      isToday: "" + year + month + now.getDate()
    });
    this.getInfo();
    this.getPoints();
    let user = app.$getUser();
    this.getSpread();
    this.getStore();
    this.setData({
      authoriz: xhs.getStorageSync("authoriz")
    });

    //获取小程序用户端菜单配置信息
    app.$getData("/user/info/get-user-menu", {}).then(data => {
      if (data.errCode == 0) {
        data = data.data;
        let isNewGoods = false;
        let menus = data.map(d => {
          let isMessage = false;
          if (d.webHash == "#/msg/") {
            isMessage = true;
          }
          return {
            name: d.name,
            icon: d.materialId,
            url: d.webHash,
            isMessage
          };
        });
        menus.forEach((t, index) => {
          if (t.url.indexOf("#/activity/newList") >= 0) {
            isNewGoods = true;
            menus.splice(index, 1);
          }
        });
        this.setData({
          isNewGoods,
          user,
          menus,
          uuid: new Date().getTime()
        });
      } else {
        xhs.showToast({
          icon: "none",
          title: data.errInfo
        });
      }
    }).catch(err => {
      xhs.showToast({
        icon: "none",
        title: "网络不给力,错误代码: " + JSON.stringify(err)
      });
    });
    initFn().then(data => {
      this.initGetDataFn(data);
    });
    app.$getSuccessData("/user/vip-card/get-master-id", {}, false).then(data => {
      this.setData({
        cardId: data.cardId
      });
    });
    this.getOrganizationInfo(xhs.getStorageSync("user").topOrgId);
  },
  /**
   * 组件的初始数据
   */
  data: {
    appId: $extConfig.appId || $config.appId,
    meQrcode: `${$resHost}/img/indexPage/meQrcode.png`,
    loginImg: `${$resHost}/img/indexPage/pg_N.png`,
    person_center_img: `background: url(${$resHost}/img/personal/personal_bg.jpg) no-repeat center`,
    edit_icon: `${$resHost}/img/indexPage/_pen.png`,
    sub_icon: `${$resHost}/img/indexPage/me_13.png`,
    storeImg: `${$resHost}/img/miniprogram/home/storesImg.png`,
    storeBg: `${$resHost}/img/miniprogram/home/storesBg.png`,
    vipImg: `https://res.gde3f.com/upload/images/20241225/7e8ddb3b77dd4487b53d86eb408aa425.png`,
    ewmImg: `https://res.gde3f.com/upload/images/20241225/99c1aa827b8647f1925dc766b5ccb543.png`,
    defaultImg: `${$resHost}/img/default_header.jpg`,
    M_icon: `${$resHost}/img/miniprogram/TweetNote/note8.png`,
    self1: `${$resHost}/img/indexPage/self1.png`,
    self2: `${$resHost}/img/indexPage/self2.png`,
    self3: `${$resHost}/img/indexPage/self3.png`,
    self4: `${$resHost}/img/indexPage/self4.png`,
    self5: `${$resHost}/img/indexPage/self5.png`,
    self6: `${$resHost}/img/indexPage/self6.png`,
    self7: `${$resHost}/img/indexPage/self7.png`,
    self8: `${$resHost}/img/indexPage/self8.png`,
    self9: `https://res.gde3f.com/upload/images/20241225/1b3d1f513f9e4008a52e5f1c55caadcd.png`,
    self10: `https://res.gde3f.com/upload/images/20241225/5de4cf78fdb645859741d427ef6cd11a.png`,
    self11: `https://res.gde3f.com/upload/images/20241225/4862bcbe5d9541f0bf48eb08fe2a07f4.png`,
    pointImg: `${$resHost}/img/indexPage/point.png`,
    sign1: `${$resHost}/img/indexPage/sign1.png`,
    sign2: `${$resHost}/img/indexPage/sign2.png`,
    sign3: `${$resHost}/img/indexPage/sign3.png`,
    sign4: `${$resHost}/img/indexPage/sign4.png`,
    sign5: `${$resHost}/img/indexPage/sign5.png`,
    sign6: `${$resHost}/img/indexPage/sign6.png`,
    sign7: `${$resHost}/img/indexPage/sign7.png`,
    sign8: `${$resHost}/img/indexPage/sign8.png`,
    accumulateSign: [],
    dateForm: [],
    user: {},
    menus: {},
    stateSeo: false,
    authoriz: false,
    scrollLeft: 0,
    unreadMsg: 0,
    qrCode: "",
    ETime: "",
    showQrCode: false,
    isSignMask: false,
    assignSignGrantPoints: "",
    pointsValue: "",
    continuitySignCount: "",
    isSigned: true,
    pointsNew: 0,
    hasRed: false,
    isNewGoods: false,
    //是否有新商品订单
    expectTotalIncome: "",
    unShipped: 0,
    alreadyShipped: 0,
    refund: 0,
    cancel: 0,
    year: 0,
    month: 0,
    date: ["日", "一", "二", "三", "四", "五", "六"],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    isAudit: 0,
    listData: {}
  },
  /**
   * 组件的方法列表
   */
  methods: {
    copy() {
      let {
        listData
      } = this.data;
      xhs.setClipboardData({
        data: listData.code,
        success: function (res) {
          xhs.getClipboardData({
            success: function (res) {
              xhs.showToast({
                title: "复制成功"
              });
            }
          });
        }
      });
    },
    hrefQrcode() {
      let {
        listData
      } = this.data;
      xhs.navigateTo({
        url: `/pages/Employee/distribution/qrCode/qrCode`
      });
    },
    getShareFn() {
      app.$getData("/user/dealer-talent/one", {}).then(data => {
        if (data.errCode == 0) {
          this.setData({
            siteConfig: xhs.getStorageSync("config"),
            isAudit: JSON.stringify(data.data) === "[]" || data.data.status == 1 || data.data.status == 2 ? "1" : "2"
          });
          if (data.data.status) {
            if (data.data.status == 1) {} else if (data.data.status == 2) {} else {
              this.setData({
                listData: data.data
              });
            }
          }
        } else {
          xhs.showToast({
            icon: "none",
            title: data.errInfo
          });
        }
      });
    },
    getRefresh() {
      let user = app.$getUser();
      this.setData({
        authoriz: xhs.getStorageSync("authoriz"),
        user
      });
      app.isEmployeeFn();
      this.getShareFn();
      this.getRemind();
    },
    updateUser() {
      app.$getData("/user/employee/is-employee").then(data => {
        if (data.errCode == 0) {
          xhs.setStorageSync("isEmployee", data.data);
          xhs.setStorageSync("employeeInfo", data.data.employeeInfo);
          xhs.setStorageSync("user", data.data.userInfo);
          this.setData({
            user: data.data.userInfo
          });
        }
      });
    },
    dateInit: function (setYear, setMonth) {
      let {
        dateForm
      } = this.data;
      // console.log(dateForm)
      let signArr = dateForm.map(item => {
        return item.date.replace(/-/g, "");
      });
      // console.log(signArr)
      //全部时间的月份都是按0~11基准，显示月份才+1
      let dateArr = [],
        monthNum; //需要遍历的日历数组数据
      let arrLen = 0; //dateArr的数组长度
      let now = setYear ? new Date(setYear, setMonth) : new Date();
      let year = setYear || now.getFullYear();
      let nextYear = 0;
      let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
      let nextMonth = month + 1 > 11 ? 1 : month + 1;
      let startWeek = new Date(year + "/" + (month + 1) + "/" + 1).getDay(); //目标月1号对应的星期
      let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
      let obj = {};
      let num = 0;
      if (month + 1 > 11) {
        nextYear = year + 1;
        dayNums = new Date(nextYear, nextMonth, 0).getDate();
      }
      arrLen = startWeek + dayNums;
      for (let i = 0; i < arrLen; i++) {
        if (i >= startWeek) {
          num = i - startWeek + 1;
          monthNum = month + 1;
          if (monthNum.toString().length == 1) monthNum = `0${monthNum}`;
          if (num.toString().length == 1) num = `0${num}`;
          obj = {
            isToday: "" + year + monthNum + num,
            dateNum: num,
            weight: 5,
            isActive: false
          };
        } else {
          obj = {};
        }
        dateArr[i] = obj;
      }
      dateArr.forEach((item, index) => {
        signArr.forEach((item1, index1) => {
          if (item.isToday && item.isToday == item1) {
            item.isActive = true;
          }
        });
      });
      // console.log(dateArr)

      this.setData({
        dateArr: dateArr
      });
      let nowDate = new Date();
      let nowYear = nowDate.getFullYear();
      let nowMonth = nowDate.getMonth() + 1;
      let nowWeek = nowDate.getDay();
      let getYear = setYear || nowYear;
      let getMonth = setMonth >= 0 ? setMonth + 1 : nowMonth;
      if (nowYear == getYear && nowMonth == getMonth) {
        this.setData({
          isTodayWeek: true,
          todayIndex: nowWeek
        });
      } else {
        this.setData({
          isTodayWeek: false,
          todayIndex: -1
        });
      }
    },
    lastMonth: function () {
      //全部时间的月份都是按0~11基准，显示月份才+1
      let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
      let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
      this.setData({
        year: year,
        month: month + 1
      });
      this.dateInit(year, month);
    },
    nextMonth: function () {
      //全部时间的月份都是按0~11基准，显示月份才+1
      let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
      let month = this.data.month > 11 ? 0 : this.data.month;
      this.setData({
        year: year,
        month: month + 1
      });
      this.dateInit(year, month);
    },
    initGetDataFn(data) {
      this.setData({
        employeeData: data.filter(res => {
          return res.tid == "5244" || res.tid == "20350" || res.tid == "3426" || res.tid == "28843" || res.tid == "2755" || res.tid == "1565" || res.tid == "610";
        }),
        userData: data.filter(res => {
          return res.tid == "28943" || res.tid == "1565" || res.tid == "2755" || res.tid == "9381" || res.tid == "9350" || res.tid == "610" || res.tid == "2648" || res.tid == "20350";
        })
      }, () => {
        let i_num = 0,
          employeeData = this.data.employeeData,
          userData = this.data.userData;
        if (this.data.isEmployee) {
          for (let i = 0; i < employeeData.length; i++) {
            if (parseInt(employeeData[i].sendCount) < 5) {
              i_num++;
            }
          }
        } else {
          for (let i = 0; i < userData.length; i++) {
            if (parseInt(userData[i].sendCount) < 5) {
              i_num++;
            }
          }
        }
        if (i_num > 0) {
          this.setData({
            hasRed: true
          });
        }
      });
    },
    addSign() {
      let {
        isSigned
      } = this.data;
      // 判断有没有签过到  没有则签到
      if (!isSigned) {
        this.doSign();
      } else {
        this.setData({
          isSignMask: true
        });
      }
    },
    hrefNavigator() {
      xhs.navigateTo({
        url: "/pages/Subpackage/UserEdit/userEdit"
      });
    },
    hrefNavigatorgold(e) {
      let {
        coins,
        points,
        memberlevel,
        toporgid
      } = e.currentTarget.dataset;
      xhs.navigateTo({
        url: `/pages/User/Goods/MemberCenter/MemberCenter/index?points=${points}&coins=${coins}&memberLevel=${memberlevel}&topOrgId=${toporgid}`
      });
    },
    setNoAuthoriz() {
      this.setData({
        authoriz: false
      });
      xhs.setStorageSync("authoriz", false);
      xhs.removeStorageSync("sessionID");
      app._authorization();
    },
    setUpdate() {
      this.setData({
        authoriz: true
      });
      xhs.setStorageSync("authoriz", true);
      let user = app.$getUser();
      this.setData({
        user
      });
    },
    updateUserInfo() {
      xhs.getUserProfile({
        desc: "用于更新用户资料",
        // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: res => {
          xhs.showLoading({
            title: "更新中",
            mask: true
          });
          let avatar = res.userInfo.avatarUrl;
          app.$getData("/user/info/update-avatar", {
            avatar
          }).then(data => {
            if (data.errCode == 0) {
              xhs.hideLoading();
              this.setData({
                ["user.avatar"]: avatar
              });
              let deadline = new Date().getTime();
              xhs.setStorageSync("deadline", deadline);
              xhs.showToast({
                title: "更新成功",
                icon: "none"
              });
            } else {
              xhs.showToast({
                title: "更新失败",
                icon: "none"
              });
            }
          });
        },
        fail: res => {
          console.log(res);
          xhs.showToast({
            title: "更新失败",
            icon: "none"
          });
        }
      });
    },
    toManage() {
      xhs.redirectTo({
        url: $extConfig.employeeIndex || $config.employeeIndex
      });
    },
    toManageNew(e) {
      let {
        type,
        toporgid
      } = e.currentTarget.dataset;
      switch (type) {
        case "Integral":
          xhs.navigateTo({
            url: `/pages/User/Goods/Integral/list?beOrgId=${toporgid}&isEmployee=1`
          });
          break;
        case "vcard":
          xhs.redirectTo({
            url: "/pages/Employee/Vcard/vcard"
          });
          break;
      }
    },
    hrefToGoods(e) {
      let status = e.currentTarget.dataset.status;
      let arrIdx = ["unShipped", "alreadyShipped", "refund", "cancel"][status - 1];
      this.setData({
        [arrIdx]: 0
      });
      xhs.navigateTo({
        url: `/pages/WebView/webView?url=user&webHash=activity/newList/${status}/1`
      });
    },
    hrefTo(e) {
      let url = e.currentTarget.dataset.url;
      if (e.currentTarget.dataset.url) if (url.substr(0, 1) == "/") {
        xhs.navigateTo({
          url: url,
          fail() {
            xhs.switchTab({
              url: url
            });
          }
        });
      } else {
        url = url.slice(2);
        xhs.navigateTo({
          url: `/pages/WebView/webView?url=user&webHash=${url}`
        });
      }
    },
    getUser() {
      let user = app.$getUser();
      this.setData({
        user
      });
    },
    closeSign() {
      this.setData({
        isSignMask: false
      });
    },
    //获取连续签到次数
    doSign() {
      let {
        assignSignGrantPoints,
        points
      } = this.data;
      app.$getData("/user/user/do-sign").then(data => {
        if (data.errCode == 0) {
          this.setData({
            isSigned: true,
            isSignMask: true
          });
          let aTime = setTimeout(() => {
            this.setData({
              // isSignMask:false,
              points: assignSignGrantPoints + points
            });
            clearTimeout(aTime);
            this.getInfo();
            this.getDateForm().then(() => {
              this.dateInit();
            });
          }, 500);
        } else {
          xhs.showToast({
            icon: "none",
            title: data.errInfo
          });
        }
      }).catch(err => {
        // debugger
        xhs.showToast({
          icon: "none",
          title: "网络不给力,错误代码: " + JSON.stringify(err)
        });
      });
    },
    getCoupon(e) {
      let {
        coupon,
        index
      } = e.currentTarget.dataset;
      let {
        accumulateSign
      } = this.data;
      if (!accumulateSign) return;
      if (accumulateSign[index].couponReceiveStatus) return xhs.showToast({
        title: "奖励已领取！",
        icon: "none"
      });
      if (!accumulateSign[index].receiveStatus) return;
      let parme = {
        couponId: coupon,
        key: accumulateSign[index].key
      };
      app.$getData("/user/user/receive-reward", parme).then(data => {
        if (data.errCode == 0) {
          this.getInfo();
          if (data.data.couponCodeId.haveLocal) {
            return this.selectComponent("#redPack").getCouponParams({
              sceneType: "9",
              params: {
                couponCodeIds: data.data.couponCodeId.data.map(item => item.id)
              }
            }, data.data.couponCodeId.data);
          }
        } else {
          xhs.showToast({
            title: data.errInfo,
            icon: "none"
          });
        }
      });
    },
    // 获取积分
    getPoints() {
      app.$getData("/user/employee/employee-info").then(data => {
        if (data.errCode == 0) {
          this.setData({
            pointsNew: data.data.points
          });
        }
      });
    },
    // 获取积分
    getRemind() {
      app.$getData("/user/order/get-user-order-remind").then(data => {
        if (data.errCode == 0) {
          this.setData({
            unShipped: data.data.unShipped,
            alreadyShipped: data.data.alreadyShipped,
            refund: data.data.refund,
            cancel: data.data.cancel,
            refundApply: data.data.refundApply
          });
        }
      });
    },
    //获取连续签到次数
    getInfo() {
      app.$getData("/user/user/get-info").then(data => {
        if (data.errCode == 0) {
          this.setData({
            // unreadMsg: data.data.unreadMsg || 0
            assignSignGrantPoints: parseInt(data.data.assignSignGrantPoints),
            continuitySignCount: data.data.continuitySignCount,
            isSigned: data.data.isSigned,
            accumulateSign: data.data.accumulateSign,
            pointsValue: parseInt(data.data.pointsValue)
          });
        } else {
          xhs.showToast({
            icon: "none",
            title: data.errInfo
          });
        }
      }).catch(err => {
        // debugger
        xhs.showToast({
          icon: "none",
          title: "网络不给力,错误代码: " + JSON.stringify(err)
        });
      });
    },
    //累计签到日期表
    getDateForm() {
      return app.$getData("/user/user/accumulate-sign-date-form").then(data => {
        if (data.errCode == 0) {
          this.setData({
            dateForm: data.data
          });
        } else {
          xhs.showToast({
            icon: "none",
            title: data.errInfo
          });
        }
      }).catch(err => {
        // debugger
        xhs.showToast({
          icon: "none",
          title: "网络不给力,错误代码: " + JSON.stringify(err)
        });
      });
    },
    // 我的推广收益
    getSpread() {},
    //获取用户未读
    getNotRead() {},
    getStore() {
      app.$getData("/user/organization/get-user-view-org", {
        currentPage: 1,
        pageSize: 999
      }).then(data => {
        let result = data.data;
        if (data.errCode == 0) {
          this.setData({
            successData: result
          });
        } else {
          xhs.showToast({
            icon: "none",
            title: data.errInfo
          });
        }
      }).catch(err => {
        xhs.showToast({
          icon: "none",
          title: "网络不给力,错误代码: " + JSON.stringify(err)
        });
      });
    },
    spreadMass() {
      let path = `/pages/User/Spread/account?type=user`;
      xhs.navigateTo({
        url: path
      });
    },
    goShop(e) {
      let orgId = e.currentTarget.dataset.orgid;
      xhs.reLaunch({
        url: `/pages/TabBar/Home/home?orgId=${orgId}`
      });
    },
    redireTo() {
      let path = `/pages/User/Vip/detail`;
      xhs.navigateTo({
        url: path
      });
    },
    hiddenQrCode() {
      this.setData({
        showQrCode: false
      });
    },
    activation() {
      app.$getData("/user/employee/activate-employee").then(data => {
        if (data.errCode == 0) {
          getCurrentPages().pop().setData({
            employeeWaitActivateFlag: false,
            isEmployee: true
          });
          app.isEmployeeFn();
          xhs.showToast({
            icon: "none",
            title: "激活成功"
          });
        } else {
          xhs.showToast({
            icon: "none",
            title: data.errInfo
          });
        }
      });
    },
    getQrCode() {
      var now = Date.now();
      var effectveTime = xhs.getStorageSync("AccessCode").effectveTime || 0;
      var date = new Date();
      var min = date.getMinutes();
      date.setMinutes(min + 5);
      var y = date.getFullYear();
      var m = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var f = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var formatdate = h + ":" + f;
      var formatdate1 = m + "-" + d;
      var time = y + "-" + m + "-" + d + " " + h + ":" + f + ":00";
      if (now >= effectveTime) {
        app.$getData("/user/qrcode/get-mini-program-qrcode", {
          path: "pages/User/Extension/OrderVerify/index",
          effectiveTime: 5,
          params: {
            shareUserId: xhs.getStorageSync("user").id
          }
        }).then(data => {
          if (data.errCode == 0) {
            this.setData({
              qrCode: data.appQrcode,
              showQrCode: true,
              ETime: `${formatdate1} ${formatdate}`
            });
            xhs.setStorageSync("AccessCode", {
              effectveTime: Date.parse(time.replace(/-/g, "/")),
              qrCode: data.appQrcode,
              ETime: `${formatdate1} ${formatdate}`
            });
          } else {
            xhs.showToast({
              icon: "none",
              title: data.errInfo
            });
          }
        });
      } else {
        var AccessCode = xhs.getStorageSync("AccessCode");
        this.setData({
          showQrCode: true,
          qrCode: AccessCode.qrCode,
          ETime: AccessCode.ETime
        });
      }

      // }
    },
    previewImage() {
      xhs.previewImage({
        urls: [this.data.qrCode]
      });
    },
    prevent() {},
    toMy() {
      xhs.navigateTo({
        url: "/pages/Employee/distribution/home/home"
      });
    },
    getOrganizationInfo(orgId) {
      app.$getData("/user/organization/organization-info", {
        orgId: orgId
      }).then(data => {
        if (data.errCode == 0) {
          this.setData({
            qyAfterSaleId: data.data.qyAfterSaleId || "",
            qyAfterSaleStatus: data.data.qyAfterSaleStatus,
            qyAfterSaleImg: data.data.qyAfterSaleImg.length != 0 ? data.data.qyAfterSaleImg.url : this.data.qyAfterSaleImg,
            qyPreSaleId: data.data.qyPreSaleId || "",
            qyPreSaleStatus: data.data.qyPreSaleStatus,
            qyPreSaleImg: data.data.qyPreSaleImg.length != 0 ? data.data.qyPreSaleImg.url : this.data.qyPreSaleImg,
            groupChatPlugId: data.data.groupChatPlugId || "",
            groupChatSwitch: data.data.groupChatSwitch,
            groupChatPng: data.data.groupChatIcon != "" ? data.data.groupChatIcon[0].url : this.data.groupChatPng,
            qyWechatAppid: xhs.getStorageSync("config").wechatInfo.qyWechatCorpid
          });
        }
      });
    },
    toQySale(e) {
      var type = e.currentTarget.dataset.type;
      var url = "";
      if (type == "after") url = this.data.qyAfterSaleId;else url = this.data.qyPreSaleId;
      xhs.openCustomerServiceChat({
        extInfo: {
          url: url
        },
        corpId: this.data.qyWechatAppid,
        success(res) {
          console.log(res);
        },
        fail(res) {
          console.log(res);
        }
      });
    }
  }
});